import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from aws_model.athena_submit import submit
from config import hour_bucket
from sql_lambda.delete import delete
from base_class.inspect_logging import print_to_log
import datetime
import json
from aws_model.aws_stepfunc import send_task_success, send_task_failure


def ac_online_fault_record(event):
    date = event.get('p_date')
    if not date:
        beijing = datetime.timezone(datetime.timedelta(hours=7))
        date = datetime.datetime.now(tz=beijing).strftime('%Y-%m-%d-%H')
    last_hour = (datetime.datetime.strptime(date, '%Y-%m-%d-%H') - datetime.timedelta(hours=1)).strftime('%Y-%m-%d-%H')
    delete(hour_bucket, f'ads/ac_online_fault_record/p_date={date}')
    filter_date = date[0:10]
    filter_hour = date[11:13]
    table_name = sys._getframe().f_code.co_name
    sql = f'''insert into ads.ac_online_fault_record
                (
                    select
                        t.sn,t.model,
                        if(d.province is null,if(d2.province is null,concat(d3.province_name,d3.province_suffix),d2.province),d.province) as province,
                        if(d.city_name is null,if(d2.city_name is null,concat(d3.province_name,d3.province_suffix),d2.city_name),d.city_name) as city,
                        t.fault_class1,
                        f1.fault_name as fault_class1_name,
                        t.fault_class2,
                        f2.fault_name as fault_class2_name,
                        if(t2.first_report_time is not null,t2.first_report_time,t.first_report_time) as first_report_time,
                        t.last_report_time,
                        t.phone,
                        '{date}'
                    from
                         (
                        select
                            sn,model,
                            fault_class1,
                            fault_class2,
                            min(timestamp) as first_report_time,
                            max(timestamp) as last_report_time,
                            max(phone) as phone,
                            cast(max(city) as varchar) as cityid
                        from
                            (
                            select
                                sn,model,timestamp,phone,city,
                                split_part(fault,'|',1) as fault_class1,
                                TRY(split_part(fault,'|',2))  as fault_class2
                            from
                                (
                                select
                                    sn,model,timestamp,phone,city,
                                    concat(
                                      if(F1Fault = true,'F1,',''),
                                      if(F3Fault = true,'F3,',''),
                                      if(E1Fault = true,'E1,',''),
                                      if(F6Fault = true,'F6,',''),
                                      if(E4Fault = true,'E4,',''),
                                      if(E8Fault = true,'E8,',''),
                                      if(F2Fault = true,'F2,',''),
                                      if(F4Fault = true,'F4,',''),
                                      if(F5Fault = true,'F5,',''),
                                      if(fanCurrentFault = true,'E2,',''),
                                      if(F7Fault = true,'F7,',''),
                                      if(F8Fault = true,'F8,',''),
                                      if(driveboardFaultdetail is not null and driveboardFaultdetail != '',concat('DB|',driveboardFaultdetail),'')
                                    ) as faults
                                from
                                    ods.iot_ac_hour t
                                where
                                    p_date = '{filter_date}'
                                and
                                    substr(timestamp,1,13) = '{filter_date} {filter_hour}'
                                ) t
                            cross join
                                unnest(split(faults,',')) as f(fault)
                            where
                                faults is not null and faults != ''
                            ) t
                        where
                            fault_class1 is not null and fault_class1 != ''
                        group by
                            sn,model,fault_class1,fault_class2
                        ) t
                    left join
                       (
                        select
                            *
                        from
                           ads.ac_online_fault_record t
                        where
                           p_date = '{last_hour}'
                       ) t2
                    on
                        t.sn = t2.sn and t.model = t2.model and t.fault_class1 = t2.fault_class1 and t.fault_class2 = t2.fault_class2
                    left join
                        dim.district d
                    on
                        substr(t.cityid,1,6) = substr(d.districtid,1,6)
                    left join
                        dim.cities d2
                    on
                        substr(t.cityid,1,4) = substr(d2.cityid,1,4)
                    left join
                        dim.area_data d3
                    on
                        substr(t.cityid,1,2) = substr(d3.province_code,1,2)
                    left join
                        dim.ac_fault_code_mapping f1
                    on
                        t.fault_class1 = f1.fault_code and f1.level = '1'
                    left join
                        dim.ac_fault_code_mapping f2
                    on
                        f2.level = '2' and f2.parent_code = f1.fault_code and t.fault_class2 = f2.fault_code
                )'''
    athena_response = submit(sql)
    print_to_log("athena_response: ", athena_response)
    output = {"msg": f"{table_name} submit ok", "Payload": {}}
    output = json.dumps(output)
    step_response = send_task_success(tasktoken, output)
    print_to_log("step_response: ", step_response)


if __name__ == '__main__':
    try:
        event = json.loads(sys.argv[1])
        tasktoken = event.get('TaskToken')
        ac_online_fault_record(event)
    except Exception as e:
        print_to_log("athena_submit 失败")
        print_to_log("原因： ", str(e))
        send_task_failure(str(e), f'执行{sys._getframe().f_code.co_filename}错误', tasktoken)
